#import "TJCustomActionSheet.h"
#import "UIView+Corner.h"
static NSInteger const DEFAULT_CELL_HEIGHT =55 ;
@interface TJCustomActionSheet ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property (nonatomic,assign) CGFloat maxHeightRatio;
@property (nonatomic,assign) UIEdgeInsets edgeInsets;
@property (nonatomic,copy)   NSString *cancelTitle;
@property (nonatomic,copy)   NSString *title;
@property (nonatomic,copy)   NSString *message;
@property (nonatomic,assign) BOOL hideWhenSelectCell;
@property (nonatomic,assign) BOOL hideWhenTapBackView;
@property (nonatomic, assign) CGFloat cornerRadius;
@property (nonatomic, copy) NSInteger (^numberOfRowsInSection)(UITableView *tableView,NSInteger section);
@property (nonatomic, copy) UITableViewCell* (^cellForRowAtIndexPath)(UITableView *tableView, NSIndexPath *indexPath);
@property (nonatomic, copy) void(^didSelectRowAtIndexPath)(UITableView *tableView,NSIndexPath *indexPath);
@property (nonatomic, copy) CGFloat (^heightForRowAtIndexPath)(UITableView *tableView,NSIndexPath *indexPath);
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, assign) BOOL animated;
@property (nonatomic, assign) CGFloat maxHeight;
@property (nonatomic, assign) CGFloat maxTableViewHeight;
@property (nonatomic, assign) CGFloat tableViewHeight;
@property (nonatomic, strong) UIView *customBgView;
@property (nonatomic, strong) UIView *contentBgView;
@property (nonatomic, strong) UIView *titleAndMessageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
@property (nonatomic, copy) void (^didSelectBlock)(NSInteger selectIndex, NSString * _Nullable title);
@end
@implementation TJCustomActionSheet

+(void)sheetWithItems:(NSArray *)items selectBlock:(nonnull void (^)(NSInteger, NSString * _Nullable))clickBlk
{
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        TJCustomActionSheet * aActionSheet = [[TJCustomActionSheet alloc]initWithItems:items];
        aActionSheet.cancelTitle = @"Cancel";
        [aActionSheet setViewContent];
        [aActionSheet.customBgView ct_getTopCornerWithRatio:Ratio(14)];
        aActionSheet.didSelectBlock = clickBlk;
        [aActionSheet showInController:UIViewController.currentNavigationController?:UIViewController.currentTabbarController animated:YES];
}

+(void)sheetWithTitle:(nullable NSString * )title message:(nullable NSString *)message items:(nullable NSArray *)items cancelTitle:(nullable NSString *)cancelTitle selectBlock:(nonnull void (^)(NSInteger, NSString * _Nullable))clickBlk
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    TJCustomActionSheet * aActionSheet = [[TJCustomActionSheet alloc] initWithTitle:title message:message items:items cancelTitle:cancelTitle];
    aActionSheet.cancelTitle = @"Cancel";
    [aActionSheet setViewContent];
    [aActionSheet.customBgView ct_getTopCornerWithRatio:Ratio(14)];
    aActionSheet.didSelectBlock = clickBlk;
    [aActionSheet showInController:UIViewController.currentNavigationController?:UIViewController.currentTabbarController animated:YES];
}

- (instancetype)initWithItems:(NSArray *)items
{
    return [self initWithTitle:nil message:nil items:items cancelTitle:nil];
}
- (instancetype)initWithTitle:(nullable NSString * )title message:(nullable NSString *)message items:(nullable NSArray *)items cancelTitle:(nullable NSString *)cancelTitle
{
    if (self = [super initWithFrame:[[UIScreen mainScreen] bounds]]) {
        self.title = title;
        self.message = message;
        self.dataSource = items;
        self.cancelTitle = cancelTitle;
        [self setDefaultValue];
        [self setViewContent];
    }
    return self;
}
- (void)setDefaultValue
{
    self.hideWhenSelectCell = YES;
    self.hideWhenTapBackView = YES;
    self.edgeInsets = UIEdgeInsetsZero;
    self.cornerRadius = 0;
    self.maxHeightRatio = 0.8;
}
#pragma mark - button action
- (void)cancelButtonAction
{
    [self hideAnimated:self.animated];
}
#pragma mark - set view
- (void)setViewContent
{
    UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) {
        safeAreaInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
    }
    self.customBgView.frame = CGRectMake(self.edgeInsets.left, 0, UIScreenWidth - self.edgeInsets.left - self.edgeInsets.right, 0);
    CGFloat titleHeight = 0.0,messageHeight = 0.0;
    if (self.title && self.title.length > 0)
    {
        self.titleLabel.frame = CGRectMake(0, 0, self.customBgView.ct_width, DEFAULT_CELL_HEIGHT);
        self.titleLabel.text = self.title;
        self.titleLabel.font = [UIFont systemFontOfSize:17];
        titleHeight = DEFAULT_CELL_HEIGHT;
    }
    else
    {
        self.titleLabel.frame = CGRectMake(0, 0, self.customBgView.ct_width, 0);
        titleHeight = 0;
    }
    if (self.message && self.message.length > 0)
    {
        CGFloat textHeight = [self heightOfText:self.message withWidth:self.customBgView.ct_width-20 fontSize:13];
        self.messageLabel.frame = CGRectMake(10, self.titleLabel.ct_bottom + 10, self.customBgView.ct_width - 20, textHeight);
        self.messageLabel.text = self.message;
        messageHeight = textHeight + 20;
    }
    else
    {
        self.messageLabel.frame = CGRectMake(10, self.titleLabel.ct_bottom + 10, self.customBgView.ct_width - 20, 0);
        messageHeight = 0;
    }
    self.titleAndMessageView.frame = CGRectMake(0, 0, self.customBgView.ct_width, titleHeight + messageHeight);
    self.customBgView.ct_height = self.titleAndMessageView.ct_height;
    self.tableView.frame = CGRectMake(0, self.titleAndMessageView.ct_bottom, self.customBgView.ct_width, 0);
    self.maxHeight = UIScreenHeight *(self.maxHeightRatio > 0.4 ? (self.maxHeightRatio > 1.0 ? 1.0 : self.maxHeightRatio) : 0.8) - safeAreaInsets.top - safeAreaInsets.bottom;
    self.maxTableViewHeight = self.maxHeight - self.titleAndMessageView.ct_height;
    if (self.cancelTitle && self.cancelTitle.length > 0)
    {
        self.maxTableViewHeight -= (8+70);
    }
    CGFloat cellHeight = DEFAULT_CELL_HEIGHT;
    if (self.heightForRowAtIndexPath)
    {
        cellHeight = self.heightForRowAtIndexPath(self.tableView,[NSIndexPath indexPathForRow:0 inSection:0]);
    }
    if (self.dataSource.count * cellHeight > self.maxTableViewHeight)
    {
        self.tableViewHeight = self.maxTableViewHeight;
        self.tableView.scrollEnabled = YES;
    }
    else
    {
        self.tableViewHeight = self.dataSource.count * cellHeight;
        self.tableView.scrollEnabled = NO;
    }
    self.tableView.ct_height = self.tableViewHeight;
    self.customBgView.ct_height += self.tableViewHeight;
    self.contentBgView.frame = CGRectMake(0, 0, self.customBgView.ct_width, self.titleAndMessageView.ct_height + self.tableView.ct_height);
    if (self.cancelTitle && self.cancelTitle.length > 0)
    {
        UIView * aSepView = [[UIView alloc]initWithFrame:CGRectMake(0, self.contentBgView.ct_bottom, self.customBgView.ct_width, 8)];
        aSepView.backgroundColor = [UIColor color333];
        [self.customBgView addSubview: aSepView];
        self.cancelButton.frame = CGRectMake(0, self.contentBgView.ct_bottom + Ratio(8),  self.customBgView.ct_width, DEFAULT_CELL_HEIGHT);
        [self.cancelButton setTitle:self.cancelTitle forState:UIControlStateNormal];
        self.customBgView.ct_height += (70+ aSepView.ct_height);
    }
    self.customBgView.ct_height += safeAreaInsets.bottom;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
    tapGesture.delegate = self;
    [self addGestureRecognizer:tapGesture];
}
- (void)refreshView
{
    [self setViewContent];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if([touch.view isKindOfClass:[self class]])
    {
        return YES;
    }
    return NO;
}
- (void)tapGestureAction:(UITapGestureRecognizer *)tapGesture
{
    if (self.hideWhenTapBackView)
    {
        [self hideAnimated:self.animated];
    }
}
#pragma mark - show
- (void)showInController:(UIViewController *)controller animated:(BOOL)animated
{
    UIWindow * aWindow = UIApplication.sharedApplication.keyWindow;
    [aWindow addSubview:self];
    self.customBgView.ct_top = UIScreenHeight;
    self.animated = animated;
    [self showAnimated:animated];
}
#pragma mark    - show
- (void)showAnimated:(BOOL)animated
{
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    self.customBgView.alpha = 0;
    CGFloat duration = animated ? 0.3 : 0.0;
    [UIView animateWithDuration:duration animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.36];
        self.customBgView.alpha = 1;
        CGRect frame = self.customBgView.frame;
        frame.origin.y = UIScreenHeight - frame.size.height;
        self.customBgView.frame = frame;
        [self.tableView reloadData];
    }];
}
- (void)hideAnimated:(BOOL)animated
{
    CGFloat duration = animated ? 0.2 : 0.0;
    __weak __typeof(self) weakself = self;
    [UIView animateWithDuration:duration animations:^{
        weakself.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        weakself.customBgView.alpha = 0;
        CGRect frame = weakself.customBgView.frame;
        frame.origin.y = UIScreenHeight;
        weakself.customBgView.frame = frame;
    } completion:^(BOOL finished) {
        [weakself removeFromSuperview];
    }];
}
#pragma UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.numberOfRowsInSection ? self.numberOfRowsInSection(tableView,section) : self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"constomActionSheetIdentifier"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"constomActionSheetIdentifier"];
    }
    if (self.dataSource) {
        cell.textLabel.text = self.dataSource[MIN(self.dataSource.count, indexPath.row)];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = [UIColor colorFFF];
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        cell.backgroundColor = [UIColor color262626];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == self.dataSource.count-1) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, UIScreenWidth);
        }
    }
    return self.cellForRowAtIndexPath ? self.cellForRowAtIndexPath(tableView,indexPath) : cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.didSelectRowAtIndexPath ? self.didSelectRowAtIndexPath(tableView,indexPath) : nil;
    self.didSelectBlock?self.didSelectBlock(indexPath.row+1,self.dataSource[MIN(indexPath.row, self.dataSource.count)]):nil;
    if (self.hideWhenSelectCell) {
        [self hideAnimated:self.animated];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.heightForRowAtIndexPath ? self.heightForRowAtIndexPath(tableView,indexPath) : DEFAULT_CELL_HEIGHT;
}
-(void)layoutSubviews
{
    CALayer *bottomLayer = [[CALayer alloc] init];
    bottomLayer.frame = CGRectMake(0, _titleAndMessageView.ct_height - 0.5, _titleAndMessageView.ct_width, 0.5);
    bottomLayer.backgroundColor = [UIColor color333].CGColor;
    [_titleAndMessageView.layer addSublayer:bottomLayer];
    _cancelButton.layer.cornerRadius = self.cornerRadius;
    _contentBgView.layer.cornerRadius = self.cornerRadius;
    _contentBgView.clipsToBounds = YES;
}
- (CGFloat)heightOfText:(NSString *)str withWidth:(CGFloat)width fontSize:(CGFloat)fontSize
{
    NSDictionary *dict = @{NSFontAttributeName : [UIFont systemFontOfSize:fontSize]};
    CGRect r = [str boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    return r.size.height;
}
#pragma mark - getter
- (UIView *)customBgView
{
    if (!_customBgView) {
        _customBgView = [[UIView alloc] initWithFrame:CGRectZero];
        _customBgView.backgroundColor = [UIColor color262626];
        [self addSubview:_customBgView];
    }
    return _customBgView;
}
- (UIView *)contentBgView
{
    if (!_contentBgView) {
        _contentBgView = [[UIView alloc] initWithFrame:CGRectZero];
        _contentBgView.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.0];
        _contentBgView.layer.cornerRadius = self.cornerRadius;
        [self.customBgView addSubview:_contentBgView];
    }
    return _contentBgView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor color262626];
        _tableView.separatorColor = [UIColor color343434];
        [self.contentBgView addSubview:_tableView];
    }
    return _tableView;
}
- (UIView *)titleAndMessageView
{
    if (!_titleAndMessageView) {
        _titleAndMessageView = [[UIView alloc] initWithFrame:CGRectZero];
        _titleAndMessageView.backgroundColor = [UIColor color262626];
        [self.contentBgView addSubview:_titleAndMessageView];
    }
    return _titleAndMessageView;
}
- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor colorFFF];
        _titleLabel.font = [UIFont systemFontOfSize:15];
        [self.titleAndMessageView addSubview:_titleLabel];
    }
    return _titleLabel;
}
- (UILabel *)messageLabel
{
    if (!_messageLabel) {
        _messageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.textColor = [UIColor grayColor];
        _messageLabel.font = [UIFont systemFontOfSize:13];
        _messageLabel.numberOfLines = 0;
        [self.titleAndMessageView addSubview:_messageLabel];
    }
    return _messageLabel;
}
- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.layer.cornerRadius = self.cornerRadius;
        [_cancelButton setBackgroundColor:[UIColor color262626]];
        [_cancelButton setTitleColor:[UIColor colorFFF] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [self.customBgView addSubview:_cancelButton];
    }
    return _cancelButton;
}
@end
